import React, { useEffect, useState, useImperativeHandle, forwardRef } from 'react';
import { withRouter } from 'react-router-dom'
import { Card, Form, Input, Button, Radio, message, Checkbox, Select, InputNumber, Tree } from 'antd';
import BreadcrumbBox from '@/components/Base/BreadcrumbBox';
import { checkRules, useDebounceFn } from '@/utils'
import { 
  addRoleAndPermissions, 
  getPermissionList, 
  findByRoleId, 
  updateRoleAndPermissions } from '@/api/role'
import { deepclone, useSyncCallback } from '@/utils'
import './index.scss';

// eslint-disable-next-line no-unused-vars
const ChildAccount = forwardRef((props, ref) => {
  const breadcrumbList = ['角色管理', '角色管理']
  const [addForm] = Form.useForm();
  const [listOptions, setListOptions] = useState([]);
  const [info, setInfo] = useState(null);
  const [id, setId] = useState('');
  const [remark, setRemark] = useState('');
  const [name, setName] = useState('');
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState({  
    "name": "",
    "remark": "",
  })
  
  // 提交弹框表单做防抖处理
  const submitOk = useDebounceFn((values) => {
    onFinish(values)
  }, 1500, true);
  const onFinish = async (values) => {
    try {
      let params = {
        permissonIds: checkedKeys,
        halfcheck: halfcheck,
        name: values.name,
        remark: values.remark,
        id: props.params.id
      }
      console.log(params)
      let res = props.params.id ? await updateRoleAndPermissions(params) : await addRoleAndPermissions(params)
      if (res.code === 0) {
        message.destroy()
        if(props.params.id){
          message.success('修改成功')
          getInfo()
        }else{
          message.success('添加成功')
        }
      }
    } catch (error) {
      console.log(error)
    }
  };
   
   
   const getInfo = async () => {
     try {
       setInfo(null)
       setLoading(true)
       addForm.setFieldsValue({
         name,
         remark,
       })
       setData({
         name,
         remark,
       })
       let res = await findByRoleId({
         roleId: props.params.id,
       })
       if(res.code === 0) {
         setInfo(res.data)
         setCheckedKeys(res.data.permissonIds)
       }
       setLoading(false)
     } catch(error) {
       console.log(error)
     }
   }
   // 获取账号权限
  const getPermissionListHanlder = async () => {
    try {
      let res = await getPermissionList()
      if(res.code === 0) {
        let arr = []
        const setData = (data) =>{
          arr.push(parseInt(data.id))
          data.title = data.name;
          data.key = parseInt(data.id)
          if(data.children){
            data.children.forEach(val=>{
              setData(val)
            })
          }
        }
        res.data.forEach(a=>{
          setData(a)
        })
        if(!props.params.id){
          setCheckedKeys(arr)
        }
        setTreeData(res.data)
      }
    } catch(error) {
      console.log(error)
    }
  }
  // 等state改变后再执行
  const searchData = useSyncCallback(() => {
    getInfo()
  })
   // 初始化
  useEffect(() => {
    if(props.params&&props.params.id){
      setId(props.params.id)
      setName(props.params.name)
      setRemark(props.params.remark)
      searchData()
    }
    getPermissionListHanlder()
  }, [])
    
  const [treeData, setTreeData] = useState([]);
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [halfcheck, setHalfcheck] = useState([]);
  const onCheck = (checkedKeysValue,e) => {
    setCheckedKeys(checkedKeysValue);
    setHalfcheck(e.halfCheckedKeys)
  };
    
  return (
    <div className='pass-component'>
      <BreadcrumbBox list={breadcrumbList}></BreadcrumbBox>
      <div className='pass-main'>
        <Card loading={loading}>
          <div className='pass-form'>
            <Form
              name="basic"
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 16 }}
              form={addForm}
              initialValues={data}
              autoComplete="new-password"
              onFinish={submitOk}>
              <Form.Item
                label="角色名称"
                name="name"
                rules={[
                  { required: true, message: '请输入角色名称' },
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="备注"
                name="remark"
                rules={[
                  { required: true, message: '请输入备注' },
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
                <Button type="primary" htmlType="submit">
                  提交
                </Button>
                <Button style={{marginLeft: '10px'}} onClick={()=>{
                  props.setPageType("list")
                  props.setParams({
                    id: ''
                  })}
                }>
                  返回
                </Button>
              </Form.Item>
            </Form>
            {
              treeData.length>0 && 
              <Tree
                checkable
                defaultExpandAll={true}
                autoExpandParent={true}
                defaultExpandParent={true}
                onCheck={onCheck}
                checkedKeys={checkedKeys}
                treeData={treeData}
              />
            }
          </div>
        </Card>
      </div>
    </div>
  )
})
export default ChildAccount